<template>
  <div class="loans-container">
    <el-card class="loans-card">
      <h2 class="form-title">融资贷款申请</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" label-position="left" size="large">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款额度" prop="balance">
              <el-input-number v-model="form.balance" :min="500" :max="100000" :step="500" :precision="0"
                placeholder="请输入贷款额度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择贷款类型">
                <el-option label="农业生产" value="农业生产" />
                <el-option label="农机购置" value="农机购置" />
                <el-option label="农资采购" value="农资采购" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="贷款理由" prop="reason">
          <el-input v-model="form.reason" type="textarea" :rows="4" placeholder="请详细说明贷款用途和理由" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">提交申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 贷款记录列表 -->
    <el-card class="loans-card" style="margin-top: 20px">
      <h2 class="form-title">我的贷款记录</h2>
      <el-table :data="loanRecords" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="贷款ID" width="120" />
        <el-table-column prop="balance" label="贷款金额" width="120">
          <template #default="scope"> ¥{{ scope.row.balance }} </template>
        </el-table-column>
        <el-table-column prop="type" label="贷款类型" width="120" />
        <el-table-column prop="reason" label="贷款理由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="isok" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.isok)">
              {{ getStatusText(scope.row.isok) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" label="申请时间" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { addAccount, listAccountByPage } from '@/api/account'
import { useUserStore } from '@/stores/user'

const formRef = ref()
const loading = ref(false)
const tableLoading = ref(false)
const userStore = useUserStore()

const form = ref({
  balance: 1000,
  userid: userStore.userInfo.id,
  reason: '',
  type: ''
})

const loanRecords = ref([])

const rules = {
  balance: [
    { required: true, message: '请输入贷款额度', trigger: 'blur' },
    {
      type: 'number',
      min: 1000,
      max: 100000,
      message: '贷款金额必须在1000-100000之间',
      trigger: 'blur'
    }
  ],
  type: [{ required: true, message: '请选择贷款类型', trigger: 'change' }],
  reason: [
    { required: true, message: '请输入贷款理由', trigger: 'blur' },
    { min: 10, max: 200, message: '贷款理由长度在10-200个字符之间', trigger: 'blur' }
  ]
}
// 获取贷款记录
const fetchLoanRecords = async () => {
  if (!userStore.userInfo.id) return

  tableLoading.value = true
  try {
    const res = await listAccountByPage({
      current: 1,
      pageSize: 10,
      userid: userStore.userInfo.id
    })
    if (res.code === 0) {
      loanRecords.value = res.data.records
    } else {
      ElMessage.error(res.message || '获取贷款记录失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取贷款记录失败')
  } finally {
    tableLoading.value = false
  }
}

// 获取状态类型
const getStatusType = status => {
  switch (status) {
    case 0:
      return 'warning' // 待审核
    case 1:
      return 'success' // 已通过
    case 2:
      return 'danger' // 已拒绝
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = status => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '已通过'
    case 2:
      return '已拒绝'
    default:
      return '未知状态'
  }
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const res = await addAccount(form.value)
    if (res.code === 0) {
      ElMessage.success('贷款申请提交成功')
      resetForm()
      fetchLoanRecords() // 刷新列表
    } else {
      ElMessage.error(res.message || '申请提交失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '表单验证失败')
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    form.value.balance = 1000
    form.value.reason = ''
    form.value.type = ''
  }
}

onMounted(async () => {
  await userStore.fetchUserInfo()
  fetchLoanRecords()
})
</script>

<style lang="less" scoped>
.loans-container {
  width: 100%;
  max-width: 1200px;
  margin: 40px auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 500px;
}

.loans-card {
  width: 100%;
  margin: 0 auto;
  padding: 32px 24px 24px 24px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form-title {
  text-align: center;
  font-size: 26px;
  font-weight: 600;
  margin-bottom: 32px;
  color: #222;
  letter-spacing: 2px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 11px;
}
</style>
